/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2013-11-27         luwei
 */

package com.tianci.appstore.ui.control;

import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;

import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.AppStoreActivity;
import com.tianci.appstore.MoreManageActivity;
import com.tianci.appstore.controller.AppStoreMainPageController;
import com.tianci.appstore.ui.control.SkyMainPageController.OnPageChangeListener;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyCategoryData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.mainpage.OnPageBoundaryListener;
import com.tianci.appstore.ui.mainpage.SkyMyAppPage;
import com.tianci.appstore.ui.widget.SkyAppPager;
import com.tianci.appstore.ui.widget.SkyAppPager.AnimListener;
import com.tianci.appstore.ui.widget.SkyBaseAdapter;
import com.tianci.appstore.ui.widget.SkyBaseItemView;
import com.tianci.appstore.ui.widget.SkyBaseItemView.OnAppKeyListener;
import com.tianci.appstore.ui.widget.SkyCategoryBar.OnCategoryChangeListener;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.ui.widget.SkyGridAdapter;

import java.util.ArrayList;
import java.util.List;


public class SkyMyAppController extends BaseUIController implements OnAppKeyListener, AnimListener, //OnAppItemClickListener,
        OnCategoryChangeListener {
    private int mClickPos = -1;
    private int mKeyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
    private int mTurnPageRow = 0;
    private int mPrePageRow = 0;
    private SkyMyAppPage mMyAppPage = null;
    private OnPageChangeListener mPageChangeListener = null;
    private OnPageBoundaryListener mBoundaryListener = null;
    private List<SkyAppBaseData> datas;
    private boolean isChildrenMode = false;

    public SkyMyAppController(final Context context) {
        super(context);
    }

    public void setAppPager(SkyAppPager pager) {
        this.mPager = pager;
        mPager.setAnimListener(this);
    }

    public void setMyAppPage(SkyMyAppPage page) {
        this.mMyAppPage = page;
    }

    public void setPageBoundaryListener(OnPageBoundaryListener listener) {
        this.mBoundaryListener = listener;
    }

    public void setPageChangeListener(OnPageChangeListener listener) {
        this.mPageChangeListener = listener;
        if (AppStoreMainPageController.MINE.equals(AppStoreActivity.mFocusCategoryId)) {
            mMyAppPage.showPageNumAndArrow(true);
        }
    }

    private void showNextPage() {
        mCurrentPage++;
        updateTurnPageRow();
        int hiddenPageIndex = 1 - mPager.getDisplayedChild();

        List<SkyAppBaseData> temp = datas.subList(mCurrentPage * 12,
                (mCurrentPage + 1) * 12 < datas.size() ? (mCurrentPage + 1) * 12 : datas.size());
        SkyCustomLayout layout = getPage(hiddenPageIndex);
        SkyBaseAdapter adapter = layout.getAdapter();
        adapter.refreshUI(temp);

        mPager.displayNextPage();
//        mPager.showNext();
        mPager.setDisplayedChild(hiddenPageIndex);
    }

    private void updateTurnPageRow() {
        SkyCustomLayout layout = getCurrentPage();
        int vPos = layout.getBlockFirstPos(mCurrentPos);
        int col = layout.getCols();
        mPrePageRow = layout.getRows();
        mTurnPageRow = vPos / col;
    }

    private void showPrePage() {
        mCurrentPage--;
        updateTurnPageRow();
        int hiddenPageIndex = 1 - mPager.getDisplayedChild();

        List<SkyAppBaseData> temp = datas.subList(mCurrentPage * 12,
                (mCurrentPage + 1) * 12 < datas.size() ? (mCurrentPage + 1) * 12 : datas.size());
        SkyCustomLayout layout = getPage(hiddenPageIndex);
        SkyBaseAdapter adapter = layout.getAdapter();
        adapter.refreshUI(temp);

        mPager.displayPrePage();
//        mPager.showPrevious();
        mPager.setDisplayedChild(hiddenPageIndex);
    }

    public boolean onItemKeyUp(int index, boolean turnPage) {
        LogUtils.d("Controller, OnKeyLeft and the index is " + index);
        if (turnPage && mCurrentPage >= 0) {
            if (mCurrentPage == 0) {
                mCurrentPage = mTotalPage;
            }
            showPrePage();
            return true;
        }
        return false;
    }

    public void setCategoryFocus() {
        int focus = getIndexByCategoryId(AppStoreActivity.mFocusCategoryId);
        mPager.setDisplayedChild(focus);
        mCurrentPage = focus;
    }

    ;

    protected SkyCustomLayout getCurrentPage() {
        return (SkyCustomLayout) mPager.getChildAt(mPager.getDisplayedChild());
    }

    public int getCurrentPageNum() {
        return mCurrentPage;
    }

    public int getTotalPage() {
        return mTotalPage;
    }

    protected SkyCustomLayout getPage(int index) {
        return (SkyCustomLayout) mPager.getChildAt(index);
    }

    public boolean onItemKeyDown(int index, boolean turnPage) {
        LogUtils.d("Controller, OnKeyRight and the index is " + index);
        if (turnPage && mCurrentPage < mTotalPage - 1) {
            showNextPage();
            return true;
        } else if ((turnPage || index == getCurrentPage().getChildCount() - 1) && mTotalPage > 1) {
            if (mCurrentPage == mTotalPage - 1) {
                mCurrentPage = -1;
            }
            showNextPage();
            return true;
        }
        return false;
    }

    public boolean onItemKeyLeft(int index, boolean turnPage) {
        LogUtils.d("Controller, OnKeyLeft and the index is " + index);
        if (turnPage) {
            if (mCurrentPage > 0) {
                showPrePage();
                return true;
            }

        }
        return false;
    }

    public boolean onItemKeyRight(int index, boolean turnPage) {
        LogUtils.d("Controller, OnKeyRight and the index is " + index);
        if ((turnPage || index == getCurrentPage().getChildCount() - 1) && mCurrentPage < mTotalPage - 1) {
            showNextPage();
            return true;
        } else if (turnPage && mCurrentPage == mTotalPage - 1) {
            if (mBoundaryListener != null) {
                mBoundaryListener.pageBoundary(KeyEvent.KEYCODE_DPAD_RIGHT, mCurrentPos);
            }
        }
        return false;
    }

    public void showPageNumAndArrow(int current, int total, int childCount) {
        if (childCount != 0) {
            if (mPageChangeListener != null) {
                mMyAppPage.showPageNumAndArrow(true);
                mPageChangeListener.onPageChange(current, total);
            }
        } else {
            mMyAppPage.showPageNumAndArrow(false);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, int index, boolean[] turnPage) {
        mCurrentPos = index;
        mKeyCode = keyCode;
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                return onItemKeyLeft(index, turnPage[0]);
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                return onItemKeyRight(index, turnPage[2]);
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_ENTER:
                mClickPos = index;
                LogUtils.d("my app click pos is " + mClickPos);
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    public boolean onAnimStart(int current) {
        SkyBaseItemView.mKey = false;
        return false;
    }

    @Override
    public boolean onAnimEnd(int current) {
        SkyCustomLayout layer = getCurrentPage();
        int pos = getNeedFocusPos();
        if (pos != -1) {
            layer.setFocusPos(pos, true);
        }
        SkyBaseItemView.mKey = true;
        showPageNumAndArrow(mCurrentPage, mTotalPage, layer.getChildCount());
        return false;
    }

    private int getNeedFocusPos() {
        // mPrePageRow为翻页前页面的行数
        // mTurnPageRow为翻页前页面的聚焦行index
        SkyCustomLayout layout = getCurrentPage();
        int col = layout.getCols();
        int row = layout.getRows();
        if (mTurnPageRow != 0) {
            mTurnPageRow += row - mPrePageRow;
        }
        row--;
        int temprow = 0;
        if (row < mTurnPageRow) {
            temprow = row;
        } else {
            temprow = mTurnPageRow;
        }
        if (mKeyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            int pos = temprow * col;
            while (pos > 0 && (layout.getBlockViewPos(pos) == -1 || layout.getChildCount() < layout.getBlockViewPos(pos))) {
                pos = pos - col;
            }
            return layout.getBlockViewPos(pos);
        } else if (mKeyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            int pos = (temprow + 1) * col - 1;
            while (pos > 0 && layout.getBlockViewPos(pos) == -1) {
                pos--;
            }
            return layout.getBlockViewPos(pos);
        }
        return 0;
    }

    private int getCategoryPageNum(int pageSize, int appSize) {
        int temp = appSize % pageSize;
        int size = appSize / pageSize;
        if (temp != 0) {
            size++;
        }
        return size;
    }

    @Override
    public void categoryChanged(SkyCategoryData data, int keyCode) {
        onKeyDown(keyCode, 7, new boolean[]{true, true, true, true});
    }

    public boolean onResume() {
        if (getCurrentPage() != null && getCurrentPage().getChildCount() != 0 && mClickPos != -1) {
            getCurrentPage().setFocusPos(mClickPos, true);
            LogUtils.d("resume my app focus pos is " + mClickPos);
            return true;
        }
        return false;
    }

    public void reSetFocus() {
        SkyCustomLayout layout = getCurrentPage();
        if (layout != null) {
            layout.setFocusPos(0, true);
        } else {
            ((MoreManageActivity) mContext).finish();
        }
    }

    public boolean setFocus() {
        if (getCurrentPage() != null)
            return getCurrentPage().setFocusPos(mCurrentPos, true);
        else
            return false;
    }

    public void refreshContent(List<SkyAppBaseData> datas) {
        try {
            if (datas == null) {
                datas = new ArrayList<SkyAppBaseData>();
            }
            this.datas = datas;
            LogUtils.d("mytime", "refresh my app and the size is " + datas.size());
            mTotalPage = getCategoryPageNum(12, datas.size());
            mMyAppPage.reSizePager(mTotalPage > 2 ? 2 : mTotalPage);
            if (mTotalPage == 0) {
                mCurrentPage = 0;
                return;
            }
            int tempNum = mTotalPage - mCurrentPage;
            if (tempNum <= 0) {
                mCurrentPage = mCurrentPage + tempNum - 1;
            }
            List<SkyAppBaseData> temp = datas.subList(mCurrentPage * 12,
                    (mCurrentPage + 1) * 12 < datas.size() ? (mCurrentPage + 1) * 12 : datas.size());
            SkyCustomLayout layout = getPage(0);
            SkyBaseAdapter adapter = layout.getAdapter();
            adapter.refreshUI(temp);
            mPager.setDisplayedChild(0);

            int childCount = 0;
            if (getCurrentPage() != null)
                childCount = getCurrentPage().getChildCount();
            showPageNumAndArrow(mCurrentPage, mTotalPage, childCount);

            if (isChildrenMode)      // 如果是儿童模式，需要子view获取焦点
            {
                SkyCustomLayout layer = getCurrentPage();
                if (layer.getChildCount() > 0)
                    layer.setFocusPos(0, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void refreshMyAppCorner(SkyListAppData data){
        int count = mPager.getChildCount();
        for (int i = 0; i < count; i++){
            boolean flag = false;
            SkyCustomLayout layout = (SkyCustomLayout)mPager.getChildAt(i);
            SkyGridAdapter adapter = (SkyGridAdapter)layout.getAdapter();
            List<SkyBaseItemView> blocks = adapter.getItemViews();
            for (SkyBaseItemView item : blocks){
                if(item.getData().getPackageName().equals(data.getPkgName())){
                    item.update(data);
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
        }
        for (SkyAppBaseData temp : datas){
            if (data.getPackageName().equals(temp.getPackageName())) {
                ((SkyListAppData) temp).updateBean = data.updateBean;
                LogUtils.d("corner","update corner" + temp.getTitle());
            }
        }

    }

    public void setChildrenMode(boolean childrenMode) {
        this.isChildrenMode = childrenMode;
    }

    @Override
    public String getCommand() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getScene() {
        // TODO Auto-generated method stub
        return null;
    }
}
